package org.xmls.common.base.exception.enums;

import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.HashMap;
import java.util.Map;

@Getter
@AllArgsConstructor
public enum GlobalErrCodeEnum {

    SUCCESS(0, "success"),

    PARAM_ERROR(400, "请求参数错误"),
    NOT_LOGIN(401, "账号未登录"),
    TOKEN_EXPIRED(402, "token已过期"),
    PERMISSION_DENIED(403, "没有该操作权限"),
    NOT_FOUND(404, "请求未找到"),
    METHOD_NOT_ALLOWED(405, "请求方法不正确"),
    LOCKED(423, "请求失败，请稍后重试"), // 并发请求，不允许
    TOO_MANY_REQUESTS(429, "请求过于频繁，请稍后重试"),
    INTERNAL_SERVER_ERROR(500, "系统异常"),
    COMMON_ERROR(5000, "请求失败"),
    ;

    private final int code;
    private final String message;

    private static final Map<Integer, String> CODE_TO_MESSAGE_MAP = new HashMap<>();

    static {
        for (GlobalErrCodeEnum errCodeEnum : GlobalErrCodeEnum.values()) {
            CODE_TO_MESSAGE_MAP.put(errCodeEnum.getCode(), errCodeEnum.getMessage());
        }
    }

    public static String getMessage(int code) {
        return CODE_TO_MESSAGE_MAP.getOrDefault(code, COMMON_ERROR.getMessage());
    }

    public static GlobalErrCodeEnum getByCode(int code) {
        for (GlobalErrCodeEnum errCodeEnum : values()) {
            if (errCodeEnum.getCode() == code) {
                return errCodeEnum;
            }
        }
        return COMMON_ERROR;
    }
}
